import React, { useEffect, useMemo, useState } from 'react'
import { SearchBar, Card, Button, Skeleton, Dialog, Toast } from 'antd-mobile'
import { useLocation, useNavigate } from 'react-router-dom'
import TopNavbar from '../../components/TopNavbar'
import styles from './index.module.css'
import { fetchDepartments, searchDoctors, fetchSlots, submitBooking, pushRecentDoctor, getRecentDoctors } from '../../services/registerService'
import { logClick, logExposure } from '../../services/tracking'

const Register = () => {
  const navigate = useNavigate()
  const location = useLocation()
  const areaId = location.state?.areaId
  const [loading, setLoading] = useState(true)
  const [depts, setDepts] = useState([])
  const [activeDept, setActiveDept] = useState(null)
  const [activeSubDept, setActiveSubDept] = useState(null)
  const [keyword, setKeyword] = useState('')
  const [doctors, setDoctors] = useState([])
  const [searching, setSearching] = useState(false)
  const [recent, setRecent] = useState([])

  useEffect(() => {
    fetchDepartments({ areaId }).then(list => {
      setDepts(list)
      const d = list[0]
      setActiveDept(d?.id || null)
      setActiveSubDept(d?.children?.[0]?.id || null)
    }).finally(() => setLoading(false))
    setRecent(getRecentDoctors())
  }, [areaId])

  useEffect(() => {
    setSearching(true)
    searchDoctors({ keyword, deptId: activeSubDept, areaId }).then(res => {
      setDoctors(res)
      logExposure('挂号_医生列表曝光', { 数量: res.length })
    }).finally(() => setSearching(false))
  }, [keyword, activeSubDept, areaId])

  const activeDeptObj = useMemo(() => depts.find(d => d.id === activeDept), [depts, activeDept])

  const handleBook = async (doctor) => {
    try {
      const slots = await fetchSlots(doctor.id)
      if (!slots.length) {
        Toast.show({ content: '该医生今日无号源', position: 'center' })
        return
      }
      const pick = slots[0]
      const ok = await Dialog.confirm({ content: `确认预约 ${doctor.name}（${doctor.title}）\n时间：${pick.time}\n费用：¥${doctor.fee}` })
      if (!ok) return
      const result = await submitBooking({ doctorId: doctor.id, slotId: pick.id })
      pushRecentDoctor({ id: doctor.id, name: doctor.name, title: doctor.title })
      logClick('挂号_提交', { 医生: doctor.id, 时段: pick.id })
      navigate('/register/result', { state: { success: result.success, bookingId: result.bookingId, payAmount: result.payAmount, doctor, slot: pick } })
    } catch (err) {
      const msg = err?.message || '预约失败，请稍后重试'
      Toast.show({ content: msg, position: 'center' })
    }
  }

  return (
    <div className={styles.page}>
      <TopNavbar title="科室列表" showBack onBack={() => navigate(-1)} />

      {/* 顶部院区卡片与切换 */}
      <div className={styles.container}>
        <div className={styles.areaCard}>
          <div className={styles.areaIcon}>📍</div>
          <div className={styles.areaInfo}>
            <div className={styles.areaName}>四川省保健院{areaId === 'a2' ? '北苑' : areaId === 'a3' ? '体检中心' : '南苑'}</div>
            <div className={styles.areaAddr}>四川省成都市锦江区画溪路666号</div>
          </div>
          <div className={styles.areaSwitch} onClick={() => navigate('/register/areas')}>切换院区 ›</div>
        </div>
        <div className={styles.askBox} onClick={() => navigate('/customer-service')}>
          不知道挂什么科，问问智能客服？<span className={styles.askLink}>去咨询</span>
        </div>
      
        <div className={styles.search}><SearchBar value={keyword} onChange={setKeyword} placeholder="搜索医生姓名或科室" /></div>

        {/* 最近挂号医生 */}
        {recent && recent.length > 0 && (
          <div className={styles.recentWrap}>
            <div className={styles.recentTitle}>最近挂号医生</div>
            <div className={styles.recentList}>
              {recent.map(item => (
                <div key={item.id} className={styles.recentItem} onClick={() => setKeyword(item.name)}>
                  <span className={styles.recentAvatar}>👤</span>
                  <span>{item.name}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* 科室双列布局 */}
        {loading ? (
          <Skeleton.Paragraph animated lineCount={4} />
        ) : (
          <div className={styles.deptLayout}>
            <div className={styles.deptLeft}>
              {depts.map(d => (
                <div
                  key={d.id}
                  className={`${styles.deptItem} ${d.id === activeDept ? styles.deptActive : ''}`}
                  onClick={() => {
                    setActiveDept(d.id)
                    setActiveSubDept(d.children?.[0]?.id || null)
                  }}
                >
                  {d.name}
                </div>
              ))}
            </div>
            <div className={styles.deptRight}>
              {activeDeptObj?.children?.map(sd => (
                <div
                  key={sd.id}
                  className={styles.subRow}
                  onClick={() => {
                    setActiveSubDept(sd.id)
                    navigate('/register/doctors', { state: { deptId: sd.id, areaId, deptName: sd.name } })
                  }}
                >
                  <div className={`${styles.subName} ${sd.id === activeSubDept ? styles.subActive : ''}`}>{sd.name}</div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* 医生列表 */}
        {searching ? (
          <div className={styles.doctorList}>
            {Array.from({ length: 3 }).map((_, i) => (
              <Card key={i} className={styles.doctorCard}>
                <Skeleton.Title animated />
                <Skeleton.Paragraph animated lineCount={2} />
              </Card>
            ))}
          </div>
        ) : (
          <div className={styles.doctorList}>
            {doctors.length === 0 ? (
              <div className={styles.empty}>暂无相关医生</div>
            ) : doctors.map(d => (
              <Card key={d.id} className={styles.doctorCard}>
                <div className={styles.docHeader}>
                  <div className={styles.avatar}>{d.avatar}</div>
                  <div className={styles.docMeta}>
                    <div className={styles.docName}>{d.name} · {d.title}</div>
                    <div className={styles.docDept}>{d.deptName}</div>
                    <div className={styles.docSchedule}>{d.schedule}</div>
                  </div>
                  <div className={styles.docFee}>¥{d.fee}</div>
                </div>
                <div className={styles.docFooter}>
                  <div className={styles.badges}>
                    <div className={styles.remain}>{d.remain > 0 ? `剩余号源 ${d.remain}` : '号源已满'}</div>
                    {d.supportIM && <div className={styles.tag}>支持问诊</div>}
                  </div>
                  <Button color='primary' size='small' disabled={d.remain <= 0} onClick={() => handleBook(d)}>立即挂号</Button>
                </div>
              </Card>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}

export default Register


